package link.tengfei.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	public static void addCookie(String cookieName, int time, HttpServletRequest request, HttpServletResponse response,
			String doc_username, String doc_password) {
		Cookie cookie = getCookieByName(request, cookieName);
		// 如有该项目保存用户名，密码的cookie，有则更改，无则新建
		if (cookie != null) {
			cookie.setValue(doc_username + "#" + doc_password);
		} else {
			cookie = new Cookie(cookieName, doc_username + "#" + doc_password);

		}
		// 设置cookie有效时间
		cookie.setMaxAge(time);
		// 设置cookie的作用范围
		cookie.setPath(request.getContextPath());

		response.addCookie(cookie);
	}

	public static Cookie getCookieByName(HttpServletRequest request, String cookieName) {
		// 从requset中获取当前项目的所有作用cookie
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			// 遍历所有cookie
			for (Cookie cookie : cookies) {
				// 根据cookie的名字获取cookie，并返回
				if (cookie.getName().equals(cookieName)) {
					return cookie;
				}
			}
		}
		return null;
	}
}
